<?php 
	include($_SERVER['DOCUMENT_ROOT']."/headerins.php");
	include($_SERVER['DOCUMENT_ROOT']."/headerFrame.php");


echo '

<script>
var i = 1;

function Save(){


	var desc = document.getElementById("Description");
	if(desc != null){
		if(desc.value == ""){ 
			desc.focus();
			alert("Заполните поле: Название");
			return;
		}
	}

	var createDT = document.getElementById("createDT");
	if(createDT != null){
		if(createDT.value == ""){ 
			createDT.focus();
			alert("Заполните поле: Дата");
			return;
		}
	}

	var userIDTo = document.getElementById("userIDTo");
	if(userIDTo != null){
		if(userIDTo.value == ""){ 
			userIDTo.focus();
			alert("Заполните поле: Дата");
			return;
		}
	}

	// go saving positions
	//save header


var u = "/core/Order/OrderAction.php?action=create&userIDTo="+userIDTo.value+"&createDT="+createDT.value+"&Description="+desc.value;

$.ajax({
	type: "POST",
	url: u,
	data: $(this).serialize(),
	success:function(response){


				var table = document.getElementsByName("positions").item(0);
				if(table != null){
					var rowCount = table.rows.length;
						for(var i=1; i < rowCount; i++) {
							var row = table.rows[i];
							var code = row.cells[1].innerHTML;
							var qty = row.cells[5].innerHTML;	
							var price1 = row.cells[3].innerHTML;	
							var ball = row.cells[4].innerHTML;	

							var ss = $.parseJSON(response);
							var orderID = ss.LastID;

							//if(irow!=null){
								var uline = "/core/Order/OrderLineAction.php?action=create"
								+"&code="+code
								+"&orderID="+orderID
								+"&qty="+qty
								+"&price1="+price1
								+"&ball"+ball;								


									$.ajax({
										type: "POST",
										url: uline,
										data: $(this).serialize(),
										success:function(response){
											//getPage('."'".'/core/Order/OrderView.php'."'".');			
										},
										error: function(request, status, error){
											alert(request.responseText);
										}
										});


							//}
						}
				}




		//getPage('."'".'/core/Order/OrderView.php'."'".');			
	},
	error: function(request, status, error){
		alert(request.responseText);
	}
	});

	alert("Данные успешно сохраненны.");
	getPage('."'".'/core/Order/OrderView.php'."'".');

}

/*
function Save(){

var orderID; 

	var desc = document.getElementById("Description");
	if(desc != null){
		if(desc.value == ""){ 
			desc.focus();
			alert("Заполните поле: Название");
			return;
		}
	}

	var createDT = document.getElementById("createDT");
	if(createDT != null){
		if(createDT.value == ""){ 
			createDT.focus();
			alert("Заполните поле: Дата");
			return;
		}
	}

	var userIDTo = document.getElementById("userIDTo");
	if(userIDTo != null){
		if(userIDTo.value == ""){ 
			userIDTo.focus();
			alert("Заполните поле: Дата");
			return;
		}
	}

	// go saving positions
	//save header

	$.getJSON("/core/Order/OrderAction.php?action=create&userIDTo="+userIDTo.value+"&createDT="+createDT.value+"&Description="+desc.value, function(data){
	
//		if(data.Result == "OK"){
//			try{
				var table = document.getElementsByName("positions").item(0);
				if(table != null){
					var rowCount = table.rows.length;
						for(var i=1; i < rowCount; i++) {
							var row = table.rows[i];
							var code = row.cells[1].innerHTML;
							var qty = row.cells[5].innerHTML;	
							var price1 = row.cells[3].innerHTML;	
							var ball = row.cells[4].innerHTML;	
							var orderID = data.LastID;
							
							r = $.getJSON("/core/Order/OrderLineAction.php?action=create"
								+"&code="+code
								+"&orderID="+orderID
								+"&qty="+qty
								+"&price1="+price1
								+"&ball"+ball								
								, 
							function(data){
								console.log(data + ":" + success);
							});

						}
				}
		
		//	}catch(e){
		//		alert(e)	
		//	}
			getPage('."'".'/core/Order/OrderView.php'."'".');
			//alert("record saved");
	//	}

        });
	
}
*/

function addRow(){

	var code = document.getElementById("MaterialID");
		
    $.getJSON("/core/Order/getMatDetail.php?code="+code.value, function(data){

	console.log("ok: " + data.result);

	if(data.result == "ok"){

		console.log("step1");

			var t = document.getElementsByName("positions").item(0);
			var code = document.getElementById("MaterialID");
			var qty = document.getElementById("qty");

			if(code != null && t != null){
				var row = t.insertRow(1);
				var cnumber = row.insertCell(0);
				var ccode = row.insertCell(1);
				var cname = row.insertCell(2);
				var cprice = row.insertCell(3);				
				var cball = row.insertCell(4);
				var cqty = row.insertCell(5);
				var deleteRow = row.insertCell(6);

				cnumber.innerHTML = i;
				ccode.innerHTML = data.Code;
				cname.innerHTML = data.MatName;
				cprice.innerHTML = data.Price1;
				cball.innerHTML = data.Ball;
				cqty.innerHTML = qty.value;
				deleteRow.innerHTML = "	<img src='."'".'/../images/delete.png'."'".' alt='."'".'Удалить'."'".' width=16 height=16	 onclick='."'".'deleteRow(" + i +")'."'".' >";
	
				i++;
			}
	}

        });
}

function deleteRow(index){
	try{
		if(index != 0){		
			var table = document.getElementsByName("positions").item(0);
			if(table != null){
				var rowCount = table.rows.length;
					for(var i=0; i < rowCount; i++) {
						var row = table.rows[i];
						var lindex = row.cells[0].innerHTML;	
						if(lindex != null && lindex == index){
							table.deleteRow(i);
							return;
						}
					}
				
			}
		}
	}catch(e){
		alert(e)	
	}
}

function mm(){
	document.getElementById("qty").focus();
	document.getElementById("qty").value="";
}

function co(){
	addRow();
	document.getElementById("MaterialID").value="";
	document.getElementById("MaterialID").focus();
}


 $(function() {
	$( "#createDT" ).datepicker();
});

</script>

<body>

	<div id="contextCaption">Добавление заказа. </div>
        <div id="response"></div>
        <hr>
	<div id="contextCaption">Заголовок заказа. </div>
        <form method="POST">
            <table border="0" id="contextGrid" cellspacing="0">
               <tr>
			<th>
				<label for="Description">Название</label>
				<td><input type="text" width="200"     id="Description" ></td>
			</th>
		</tr>
		<tr>
			<th>
				<label for="userIDTo">Покупатель</label>
				<td>
					<select id="userIDTo" style="width: 100%;">
';
					$result = mysql_query('
						SELECT Id, lastname FROM users where ParentNumber = '.$_SESSION['g_number']);
					
					while($row = mysql_fetch_array($result)){
							echo '<option value='; echo '"'.$row['Id'].'"'; echo '">'; echo $row['lastname']; echo '</option>';
						}
					
echo '		
					</select>
				</td>	
		</tr>
		<tr>
                    <th>
			<label for="createDT">Дата</label> 
			<td>
				<input type="text" id="createDT" >
			</td>
		</th>
		</tr>
            </table>
	
	<hr>
	<div id="contextCaption">Позиции заказа. </div>	
	
	<label style="padding-left: 10px;">Введите номер товара и нажмите Enter, далее можете ввести кол-ва товара, потом снова на Enter и так далее. </label>
	<br>
	<table border=0 id="contextGrid">
	<tr>
	<td><label for="MaterialID" style="padding-left: 10px; padding-top: 2px; padding-right: 2px;">Введите номер товара </label></td>
	<td style="width: 80%; "><input list="Materials" name="Material" id="MaterialID" onchange="mm()" size="100px" style="width: 100%; float: left;">
	<datalist id="Materials">
';					
		$result = mysql_query("
			SELECT 
				Code, Name
			FROM material");
	
		$rows = array();
		while($row = mysql_fetch_array($result)){
		   echo '<option value="'.$row['Code'].'">'.$row['Code'].' - '.$row['Name'].'</option>';  
		}
echo '
	</datalist></td>	
	</tr>
	<tr>
		<td><label for="qty" style="padding-left: 10px; padding-top: 2px; padding-right: 2px;">Введите кол-во </label></td>
		<td style="width: 80%; "><input type="input" id="qty" onchange="co()" size="10" ></td>
	</tr>
</table>
<br>
<table name="positions" id="contextGrid" border="0" cellspacing="0" style="width: 80%;">
	<tr>
		<th style="width: 10px">№</th>
		<th style="width: 40px">Код</th>
		<th >Наименование товара</th>
		<th style="width: 50px">Цена</th>
		<th style="width: 50px">Балл</th>
		<th style="width: 50px">Кол-во</th>
		<th style="width: 10px">Уд.</th>
	</tr>
</table>
<br>


<hr>
            <input id="button" type="Button"  value="Закрыть" title="Закрыть не сохраняя изменения" onclick="getPage('."'".'/core/Order/OrderView.php'."'".')">            
            <input id="button" type="Button" value="Сохранить" title="Сохранить" onclick="Save()" >
	</form>

</body>
';



/*
	echo '		
		<div id="contextCaption">Добавление заказа. </div>
        <div id="response"></div>
        <hr>
        <form action="javascript:Request('."'".'Order'."'".', '."'".'update'."'".', '."'".''."'".')" method="POST">
            <table border="0" id="contextGrid" cellspacing="0">
';

				$ID = 0;
				$Description = 0;
				$createDT = 0;
				$UserIDTo = 0;

				if(!isset($_GET['id']) or $_GET['id'] <= 0){
					$t = $_SESSION['userID'];
					$sql = " INSERT INTO `order` (userID, CreateDT) VALUES(".$t.", now() ); ";
					$result = mysql_query($sql) || die(mysql_error());
					if (!$result) {
						die('mlm.order.create: ' . mysql_error(). $sql);
					}

					$sql = 'SELECT ID FROM `order` WHERE ID = LAST_INSERT_ID()';
					$result = mysql_query($sql);
					while($row = mysql_fetch_array($result)){
						$ID = $row['ID'];
					}
				}else			
					$ID = $_GET['id'];

                          $sql = '
								SELECT
									o.id
									,o.userID
									,o.userIDTo
									,o.createDT
									,o.description
								FROM
									`order` o where o.id =  
                          '.$ID;
                          $result = mysql_query($sql);
                          while($row = mysql_fetch_array($result)){
							$Description = $row['description'];
							$UserIDTo = $row['userIDTo'];
							$createDT = $row['createDT'];
						  }

echo '     
               <tr><th><label for="Description">Название</label><input type="text" width="200"     id="Description"   value='.$Description.'></th></tr>
					<th><label for="userIDTo">Покупатель</label>
					<select id="userIDTo">
';
								$result = mysql_query('
									SELECT 
										Id, lastname
									FROM users');
								
								while($row = mysql_fetch_array($result)){
									if($row['Id'] == $UserIDTo){
			 echo '	<option selected="selected" value='; echo '"'.$row['Id'].'"'; echo '">'; echo $row['lastname']; echo '</option>';
								}else{ 
						

		echo '<option value='; echo '"'.$row['Id'].'"'; echo '">'; echo $row['lastname']; echo '</option>';

								}}
echo '		
					</select>	
                    <th><label for="createDT">Дата</label> <input type="text"       id="createDT"   value="'.$createDT.'"></th>
            </table>
            <hr>
				<table border="0" id="contextGrid" cellspacing="0">
				<thead>
					<th>№</th>
					<th>№ Материала</th>
					<th>Наименование</th>
					<th>Количество</th>
					<th>Цена</th>
					<th>Сумма</th>
					<th>Балл</th>
					<th>Баллы</th>
				   <th>Изм</th>
				   <th>Уд</th>
				</thead>
				<tbody>
';
                          $sql = '
								SELECT 
									ol.OrderLineID
									,ol.OrderID
									,m.code
									,m.name
									,ol.Qty
									,ol.Price1
									,(ol.Price1 * ol.qty) summ
									,ol.Ball
									,(ol.Ball * ol.qty) balls
								FROM
										orderline ol
										inner join material m on m.id = ol.MaterialID
								where ol.orderID = '.$ID
                          ;
                          $result = mysql_query($sql);
					if (!$result) {
						die('mlm.order.create: ' . mysql_error(). $sql);
					}
						  $pos = 0;

						while($row = mysql_fetch_array($result)){
							$pos++;	
                              echo "<tr>";
                              echo "<td> " .$pos. "</td>";
                              echo "<td> " . $row['code'] . "</td>";                                  
							  echo "<td> " . $row['name'] . "</td>";
							  echo "<td> " . $row['Qty'] . "</td>";
							  echo "<td> " . $row['Price1'] . "</td>";
							  echo "<td> " . $row['summ'] . "</td>";
							  echo "<td> " . $row['Ball'] . "</td>";
							  echo "<td> " . $row['balls'] . "</td>";
							  echo "<td>  
	<img onclick=".'"'."getPage('/core/Order/OrderLineUpdate.html?OrderID=".$row['OrderID']."&OrderLineID=".$row['OrderLineID']."')".'"'." src='/../images/edit.png' alt='Изменить' width=16 height=16> </td>";
                              echo "<td>  
	<img onclick=".'"'."Request('OrderLine','delete', '".$row['OrderLineID']."')".'"'." src='/../images/delete.png' alt='Удалить' width=16 height=16> </td>";

							echo "</tr>";				
						}
				echo '
				</tbody>
				</table>
				<br>
				<input id="button" type="button" value="Добавить" title="Добавить позицию"
				onclick="getPage('."'".'/core/Order/OrderLineCreate.html?orderID='.$ID.')"
				>
				<br>
			<hr>
            <div id="result"><div>
            <input type="hidden"  id="orderID" value="<?php echo $ID; ?>">
            <input id="button" type="Button"  value="Отмена" title="Отменить измение" onclick="getPage('."'".'/core/Order/OrderView.html'."'".')">            
            <input id="button" type="submit" value="Сохранить" title="Сохранить измение">
        </form>';

*/
